<template>
    <TheElDialog :title="title" :visible.sync="centerDialogVisible" @close="handleCenterDialogClose" v-bind="$attrs">
        <el-form
            @submit.native.prevent
            ref="formRule"
            :model="form"
            :rules="rules"
            :label-width="isMobile ? '80px' : '120px'"
        >
            <el-form-item prop="toName" label="收款名称">
                <el-input :disabled="isDetail" v-model="form.toName" clearable placeholder="请填写收款名称"></el-input>
            </el-form-item>
            <el-form-item prop="toMoney" label="收款金额">
                <el-input :disabled="isDetail" v-model="form.toMoney" clearable placeholder="请填写收款金额"></el-input>
            </el-form-item>
            <el-form-item prop="toStatus" label="收款状态">
                <el-select
                    :disabled="isDetail"
                    type="text"
                    v-model="form.toStatus"
                    placeholder="请填写收款状态"
                    clearable
                    style="width: 100%"
                >
                    <template v-for="item in revenueOptionsStatus">
                        <el-option :label="item.label" :value="item.value" :key="item.value"></el-option>
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item prop="toTime" label="收款时间">
                <el-date-picker
                    :disabled="isDetail"
                    v-model="form.toTime"
                    type="datetime"
                    clearable
                    placeholder="请填写账单借款时间"
                    :style="inputStyle"
                    :editable="isMobile ? false : true"
                    :align="isMobile ? 'right' : 'left'"
                ></el-date-picker>
            </el-form-item>
            <el-form-item prop="fromTime" label="收款到账时间">
                <el-date-picker
                    :disabled="isDetail"
                    v-model="form.fromTime"
                    type="datetime"
                    placeholder="请填写账单借款时间"
                    :picker-options="pickerOptions"
                    :style="inputStyle"
                    :editable="isMobile ? false : true"
                    :align="isMobile ? 'right' : 'left'"
                ></el-date-picker>
            </el-form-item>
            <el-form-item prop="toMode" label="收款方式">
                <el-select
                    :disabled="isDetail"
                    v-model="form.toMode"
                    placeholder="请选择收款方式"
                    multiple
                    clearable
                    style="width: 100%"
                >
                    <template v-for="item in revenueOptionsMode">
                        <el-option :label="item.label" :value="item.value" :key="item.value"></el-option>
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item prop="toAccount" label="收款账号">
                <el-input
                    :disabled="isDetail"
                    type="text"
                    v-model="form.toAccount"
                    placeholder="请填写收款账号"
                ></el-input>
            </el-form-item>

            <el-form-item prop="toType" label="收入类型">
                <el-input
                    :disabled="isDetail"
                    type="text"
                    v-model="form.toType"
                    clearable
                    placeholder="比如：工资收入"
                ></el-input>
            </el-form-item>
            <el-form-item prop="fromAccount" label="付款账号">
                <el-input
                    :disabled="isDetail"
                    type="text"
                    v-model="form.fromAccount"
                    clearable
                    placeholder="请填写付款账号"
                ></el-input>
            </el-form-item>

            <el-form-item prop="toRemark" label="备注">
                <el-input
                    :disabled="isDetail"
                    type="textarea"
                    v-model="form.toRemark"
                    clearable
                    placeholder="请填写收入备注"
                ></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button :disabled="centerDialogLoading" @click="centerDialogVisible = false">取 消</el-button>
            <el-button
                :disabled="isDetail"
                :loading="centerDialogLoading"
                type="primary"
                @click="handleSubmit('formRule')"
                >确 定</el-button
            >
        </span>
    </TheElDialog>
</template>
<script>
import moment from 'moment';
import {
    BASIC_MONEY,
    getRevenueOptionsMode,
    getRevenueOptionsStatus,
    THE_MOMENT_YYYYMMDD_HHMMSS
} from '@/utils/constant';
import {postRevenueList, putRevenueList} from '@/api/revenue';
import {validateToMoney} from './validation';
const revenueOptionsMode = getRevenueOptionsMode();
const revenueOptionsStatus = getRevenueOptionsStatus();

export default {
    name: 'RevenueDialog',
    props: {
        title: {
            type: String,
            default: ''
        },
        visible: {
            type: Boolean,
            default: false
        },
        dataSource: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            moment,
            // 新建弹窗 提交表单中
            centerDialogLoading: false,
            inputStyle: {width: '100%'},
            // 新建表单
            form: {
                id: undefined, // 数据id
                toName: '',
                toMoney: '',
                toTime: '',
                fromTime: '',
                toMode: [],
                toAccount: '',
                toStatus: '',
                toType: '',
                fromAccount: '',
                toRemark: ''
            },
            rules: {
                toName: [{required: true, message: '请填写收款名称', trigger: ['change', 'blur']}],
                toMoney: [
                    {required: true, message: '请填写收款金额', trigger: ['change', 'blur']},
                    {validator: validateToMoney, trigger: ['change', 'blur']}
                ],
                toTime: [{required: true, message: '请填写收款时间', trigger: ['change', 'blur']}],
                fromTime: [{required: true, message: '请填写收款到账时间', trigger: ['change', 'blur']}],
                toMode: [{required: true, message: '请填写收款方式', trigger: ['change', 'blur']}],
                toAccount: [{required: false, message: '请填写收款账号', trigger: ['change', 'blur']}],
                toType: [{required: true, message: '请填写收入类型', trigger: ['change', 'blur']}],
                // fromMode: [{required: true, message: '请填写付款方式', trigger: ['change', 'blur']}],
                fromAccount: [{required: false, message: '请填写付款账号', trigger: ['change', 'blur']}],
                toStatus: [{required: true, message: '请填写收款状态', trigger: ['change', 'blur']}]
                // toRemark: [{required: true, message: '请填写备注', trigger: ['change', 'blur']}]
            }
        };
    },
    computed: {
        isMobile() {
            return this.$store.getters['app/isMobile'];
        },
        pickerOptions() {
            if (this.isMobile) {
                return {};
            }
            const toTime = this.form.toTime;
            return {
                shortcuts: [
                    {
                        text: '同收款时间',
                        onClick(picker) {
                            const start = moment(toTime).format(THE_MOMENT_YYYYMMDD_HHMMSS);
                            picker.$emit('pick', start);
                        }
                    }
                ]
            };
        },
        // 收款、付款方式 options
        revenueOptionsMode() {
            return revenueOptionsMode;
        },
        // 收款、付款方式 options
        revenueOptionsStatus() {
            return revenueOptionsStatus;
        },
        isDetail() {
            return this.title === '查看收入订单';
        },
        centerDialogVisible: {
            get() {
                return this.visible;
            },
            set(val) {
                this.$emit('update:visible', val);
            }
        }
    },
    watch: {
        dataSource: {
            handler(val) {
                this.form = {
                    _id: val._id, // 数据id
                    toName: val.toName,
                    toMoney: val.toMoney,
                    toTime: val.toTime,
                    fromTime: val.fromTime,
                    toMode: val.toMode,
                    toAccount: val.toAccount,
                    toStatus: val.toStatus,
                    toType: val.toType,
                    fromAccount: val.fromAccount,
                    toRemark: val.toRemark
                };
            },
            deep: true,
            immediate: true
        }
    },
    methods: {
        // 自定义校验permissions_ids
        handlePerimissionChange() {
            this.$refs['formRule'].validateField('permission');
        },

        // 提交
        handleSubmit(formName) {
            this.$refs[formName].validate((valid, fields) => {
                const form = this.form;
                if (valid) {
                    const newItem = {
                        _id: form._id,
                        toName: form.toName,
                        toMoney: (form.toMoney - 0) * BASIC_MONEY,
                        toTime: moment(form.toTime).format(THE_MOMENT_YYYYMMDD_HHMMSS),
                        fromTime: moment(form.fromTime).format(THE_MOMENT_YYYYMMDD_HHMMSS),
                        toMode: form.toMode.join(','),
                        toAccount: form.toAccount,
                        toStatus: form.toStatus,
                        toType: form.toType,
                        fromAccount: form.fromAccount,
                        toRemark: form.toRemark || ''
                    };

                    if (this.title === '创建收入订单') {
                        this.handleCreate(newItem);
                    }
                    if (this.title === '编辑收入订单') {
                        this.handlePut(newItem);
                    }
                } else {
                    const first = Object.keys(fields)[0];
                    const items = fields[first] || [];
                    const {message} = items[0] || {};
                    this.$message({showClose: true, type: 'error', message});
                    return false;
                }
            });
        },
        // 创建
        handleCreate(newItem) {
            this.centerDialogLoading = true;
            postRevenueList(newItem)
                .then(({data: res}) => {
                    if (res.status === 201) {
                        this.$message({showClose: true, type: 'success', message: '创建成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // 更新
        handlePut(newItem) {
            this.centerDialogLoading = true;
            putRevenueList(newItem._id, newItem)
                .then(({data: res}) => {
                    if (res.status === 204) {
                        this.$message({showClose: true, type: 'success', message: '更新成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    this.$message({showClose: true, type: 'error', message: error});
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // dialog 关闭
        handleCenterDialogClose() {
            // 关闭
            this.$emit('close');
            this.$refs['formRule'].resetFields();
        }
    }
};
</script>
